//
//  NewFeatureCollectionViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/2.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureCollectionViewController: UICollectionViewController {

    //图像总数
    private let imageCount = 4
    
    //布局属性
    private let layout = TYHFlowLayout()
    
    init(){
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additiona````l setup after loading the view.
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        // Configure the cell
        cell.imageIndex = indexPath.item
    
        return cell
    }

    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //获取当前的显示的 indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        // 判断是否是末尾
        if path.item == imageCount - 1 {
            //播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startButtonAnim()
        
        }
        
        
    }

    
}
///新特性的cell
class NewFeatureCell: UICollectionViewCell {
    
    private var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
            
        }
    }
    
    func clickStartButton() {
//        print("开始")
        //切换控制器
        NSNotificationCenter.defaultCenter().postNotificationName(TYHRootViewControllerSwitchNotification, object: true)
    }
    
    //开始动画
    private func startButtonAnim() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        //禁止操作
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            //恢复默认
            self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                self.startButton.userInteractionEnabled = true
        }
        
    }
    
    //Mark: 设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
//        fatalError("init(coder:) has not been implemented")
        prepareUI()
    }
    
    //准备ui
    private func prepareUI() {
        //添加控件
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        //自动布局
        iconView.ff_Fill(contentView)
        
//        iconView.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
//        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))

    startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
//        startButton.translatesAutoresizingMaskIntoConstraints = false
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
    
    }
    
    // MARK: 懒加载
    private lazy var iconView: UIImageView = UIImageView()
    private lazy var startButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Normal)
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        
        btn.sizeToFit()
//        btn.hidden = true
        btn.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    

}




///自定义流水布局
private class TYHFlowLayout: UICollectionViewFlowLayout {
    //准备布局属性
    private override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
}




